package com.example.mmlist2;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.lifecycle.ViewModelProvider;

import com.example.mmlist2.mode.NavigationViewModel;
import com.example.mmlist2.storage.DatabaseHelper;
import com.example.mmlist2.storage.entity.Account;
import com.google.android.material.floatingactionbutton.FloatingActionButton;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class ListFragment extends Fragment {

    RecyclerView recyclerView;
    List<Map<String, Object>> mdata;
    SwipeRefreshLayout swipeRefreshLayout;


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_list, container, false);

        //获取实例
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(Objects.requireNonNull(getContext()));
        IntentFilter intentFilter = new IntentFilter("com.example.mmList2.REFRESH_LIST");
        //注册本地广播监听器
        localBroadcastManager.registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // 这里是接收到刷新广播时触发的代码
                refreshData();
            }
        }, intentFilter);

        // 初始化SwipeRefreshLayout
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh);
        // 这里是下拉刷新时触发的代码
        swipeRefreshLayout.setOnRefreshListener(this::refreshData);

        FloatingActionButton add = view.findViewById(R.id.add);
        add.setOnClickListener(view1 -> NavHostFragment.findNavController(ListFragment.this)
                .navigate(R.id.action_ListFragment_to_DetailFragment));
        mdata = getData();

        recyclerView = view.findViewById(R.id.datalist);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(new MyAdapter());

        EditText search = view.findViewById(R.id.search);

        search.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onClick(View view) {
                String str = search.getText().toString();
                if (str.trim().isEmpty()) {
                    Toast.makeText(getContext(), "请输入搜索内容", Toast.LENGTH_SHORT).show();
                    mdata = getData();
                    Objects.requireNonNull(recyclerView.getAdapter()).notifyDataSetChanged();
                } else {
                    mdata = getDataByKey(str);
                    Log.d("mdata", mdata.toString());
                    //更新数据
                    Objects.requireNonNull(recyclerView.getAdapter()).notifyDataSetChanged();
                }
            }
        });

        // 获取 ViewModel 实例
        NavigationViewModel navigationViewModel = new ViewModelProvider(requireActivity()).get(NavigationViewModel.class);

        // 设置返回按钮监听器
        requireActivity().getOnBackPressedDispatcher().addCallback(getViewLifecycleOwner(),
                new OnBackPressedCallback(true) {
                    @Override
                    public void handleOnBackPressed() {
                        // 设置标志位
                        navigationViewModel.setReturningFromListFragment(true);
                        // 返回到前一个Fragment
                        NavHostFragment.findNavController(ListFragment.this).popBackStack();
                    }
                });

        return view;
    }

    @SuppressLint("NotifyDataSetChanged")
    void refreshData() {
        // 重新从数据库获取数据
        mdata = getData();
        // 通知适配器数据已更新
        Objects.requireNonNull(recyclerView.getAdapter()).notifyDataSetChanged();
        // 停止刷新动画
        swipeRefreshLayout.setRefreshing(false);
    }

    private List<Map<String, Object>> getDataByKey(String key) {
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map;
        try {
            DatabaseHelper db = new DatabaseHelper(this.getContext());
            List<Account> accounts = db.getAccountByKey(key);
            if (accounts.isEmpty()) {
                Toast.makeText(getContext(), "没有找到相似账号", Toast.LENGTH_SHORT).show();
            } else {
                for (Account ac : accounts) {
                    map = new HashMap<>();
                    map.put("id", ac.getId());
                    map.put("title", ac.getTitle());
                    map.put("username", ac.getUsername());
                    list.add(map);
                    System.out.println(ac);
                }
            }
            db.close();
        } catch (Exception e) {
            Log.e("ListFragment", "db error");
        }
        return list;
    }

    private List<Map<String, Object>> getData() {
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map;
        try {
            DatabaseHelper db = new DatabaseHelper(this.getContext());
            List<Account> accounts = db.getAllAccounts();
            for (Account ac : accounts) {
                map = new HashMap<>();
                map.put("id", ac.getId());
                map.put("title", ac.getTitle());
                map.put("username", ac.getUsername());
                list.add(map);
                System.out.println(ac);
            }
            db.close();
        } catch (Exception e) {
            Log.e("db", "error");
        }
        return list;
    }

    //item的适配器
    class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView title, username, id;
            LinearLayout click;
            Button delete;

            //获取item对象
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                click = itemView.findViewById(R.id.click);
                id = itemView.findViewById(R.id.id);
                title = itemView.findViewById(R.id.title);
                username = itemView.findViewById(R.id.username);
                delete = itemView.findViewById(R.id.delete);
            }
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getContext()).inflate(R.layout.item, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
            if (mdata == null || position < 0 || position >= mdata.size()) {
                Log.e("onBindViewHolder", "mdata error");
                return;
            }
            Object idObj = mdata.get(position).get("id");
            if (idObj == null) {
                Log.e("onBindViewHolder", "idObj error");
                return;
            }
            int idInt = (int) idObj;
            final String id = String.valueOf(idInt);
            final String title = (String) mdata.get(position).get("title");
            final String username = (String) mdata.get(position).get("username");
            holder.id.setText(id);
            holder.title.setText(title);
            holder.username.setText(username);
            //给每个item设置点击事件
            holder.click.setOnClickListener(v -> {
                NavController navController = Navigation.findNavController(Objects.requireNonNull(getActivity()), R.id.nav_host_fragment_content_main);
                Bundle bundle = new Bundle();
                bundle.putString("id", id);
                bundle.putString("title", title);
                bundle.putString("username", username);
                navController.navigate(R.id.action_ListFragment_to_DetailFragment, bundle);
            });
            //给每个item设置删除事件
            holder.delete.setOnClickListener(v -> {
                try (DatabaseHelper db = new DatabaseHelper(getContext())) {
                    int i = db.deleteAccountById(idInt);
                    if (i > 0) {
                        //刷新数据
                        removeItem(position);
                    }
                } catch (Exception e) {
                    Log.e("delete", "删除数据错误");
                }
            });
        }

        public void removeItem(int position) {
            Log.d("removeItem", "position:" + position);
            Log.d("removeItem", mdata.toString());
            mdata.remove(position);
            notifyItemRemoved(position);
            notifyItemRangeChanged(position, getItemCount());//position item下标，data.size 更细后的数据源大小
        }

        @Override
        public int getItemCount() {
            return mdata.size();
        }

    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d("onStop", "onStop");
    }

}